#include "ThreadPoolManager.h"

namespace mpgl_engine{ namespace driver { namespace threading {

	ThreadPoolManager::ThreadPoolManager()
	{
		//Create empty thread array
		m_threads = new boost::thread* [MAX_THREAD_CNT];
		m_threadFcns = new ThreadProcedure* [MAX_THREAD_CNT];
		for(int i = 0; i < MAX_THREAD_CNT; i++)
		{
			m_threads[i] = NULL;
			m_threadFcns[i] = NULL;
		}
		//Set index to 0
		m_threadCount = 0;
	}

	ThreadPoolManager::~ThreadPoolManager()
	{
		//Delete each thread
		for(int i = 0; i < MAX_THREAD_CNT; i++)
		{
			if ( m_threads[i] != NULL)
			{
				//Wait for thread to stop
				m_threadFcns[i]->RequestStop();
				try
				{
					m_threads[i]->join();
					delete m_threads[i];
				
				}	
				catch (...)
				{
					throw "Unable to join thread!";
				}
			}
		}
		//Delete the thread array
		delete [] m_threads;
		delete [] m_threadFcns;
	}

	bool ThreadPoolManager::AddThread(ThreadProcedure* proc)
	{
		if ( m_threadCount >= MAX_THREAD_CNT )
			return false;
		m_threadFcns[m_threadCount] = (proc);
		m_threads[m_threadCount] = 
			new boost::thread( boost::bind(&ThreadProcedure::Procedure, proc) );
		m_threadCount++;
		return true;
	}

}}}